<!-- <template>
  <div id="MCodeEditor" style="height: 700px;" ref="codeRef"></div>
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor"; // 全部导入
import { ref, onMounted, toRaw, toRef, watch } from "vue";

const codeRef = ref(null);

/**
 * 定义组件属性类型
 */
interface Props {
  value: string;
  change: (v: string) => void;
}

/**
 * 给组件指定初始值
 */
const props = defineProps<Props>();
const value = toRef(props, "value");

const editor = ref<monaco.editor.IStandaloneCodeEditor | null>(null);
// 监听value 变化， 变化进行更新代码编辑器中的值
watch(value, (newValue) => {
  if (editor.value) {
    // 转成普通对象
    toRaw(editor.value).setValue(newValue);
  }
});


onMounted(() => {
  setTimeout(() => {
    
    editor.value = monaco.editor.create(codeRef.value!, {
      value: value.value || "",
      language: "java",
      minimap: {
        enabled: false, //是否显示侧边栏
      },
      colorDecorators: true, //颜色装饰器
      readOnly: false, //是否开启已读功能
      theme: "vs-dark", //主题
    });

    // 监听编辑器内容变化
    editor.value.onDidChangeModelContent(() => {
      // 触发父组件的 change 事件，通知编辑器内容变化
      props.change(toRaw(editor.value)!.getValue());
    });
  }, 100);
});
</script> -->

<template>
  <div ref="editorContainer" style="height: 60vh"></div>
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor"; // 全部导入
import { ref, onMounted, toRaw } from "vue";
import { defineProps } from "vue";
const editor = ref();
const editorContainer = ref();

interface PropsParam {
  value: string;
  language: string;
  change: (v: string) => void;
}

const props = defineProps<PropsParam>();
// const value = toRef(props,"value");

// 监听对象变化
// watch(value, (newValue) => {
//   if (editor.value) {
//     // 转成普通对象
//     toRaw(editor.value).setValue(newValue);
//   }
// });

onMounted(() => {
  editor.value = monaco.editor.create(editorContainer.value, {
    value: props.value || "",
    language: props.language || "java",
    colorDecorators: true, //颜色装饰器
    readOnly: false, //是否开启只读功能
    theme: "vs-dark", //主题
  });

  // 监听编辑器内容变化
  editor.value.onDidChangeModelContent(() => {
    // 触发父组件的 change 事件，通知编辑器内容变化
    props.change(toRaw(editor.value)!.getValue());
  });
});
</script>
